<?php

namespace app\common\model;
use app\api\model\ServerException;
use app\api\model\TokenException;
use app\api\model\UserException;
use think\facade\Cache;
use think\facade\Db;

class OrderChange extends Base
{
    // 开启自动写入时间戳字段
    protected $autoWriteTimestamp = true;

    /**
     * 申请换货
     * @param $user
     * @param $order_id
     * @param $note
     * @param $imgs
     * @return true
     * @throws ServerException
     * @throws UserException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    static public function changeApply($user,$order_id,$note,$imgs){

        $note = reInjectThree($note);
        if($note==''){
            throw new UserException('请输入补充描述，有助于商家更好的处理售后问题');
        }
        if(mb_strlen($note,'utf-8')>'100'){
            throw new UserException('补充描述请勿超过100字');
        }

        if(!is_array($imgs) || count($imgs)<1){
            throw new UserException('请至少上传一张凭证图片');
        }

        if(count($imgs)>3){
            throw new UserException('凭证图片请勿超出3张');
        }

        //订单
        $order = Db::name('order')
            ->where('id','=',$order_id)
            ->where('uid','=',$user['id'])
            ->field('id,merch_id,type,activity_type,verify_type,status,pay_price')
            ->find();
        if(!$order){
            throw new UserException('无此订单或无权操作');
        }

        if($order['type']!=2){
            throw new UserException(get_base_type(3,$order['type']).'订单不可申请换货');
        }

        if(in_array($order['status'],[-1,0])){
            throw new UserException('订单未支付，无法申请换货');
        }

        if($order['status']>=3){
            throw new UserException('订单已完成，无法申请换货');
        }

        if($order['status']<=-2){
            throw new UserException('订单已申请售后，请勿重复申请');
        }

        //换货超时时间
        $system = Settings::getSystem();
        $change_over_time = time()+($system['change_over_time']*3600);

        //系统配置
        $change = [
            'status'=>'-4',
            'old_status'=>$order['status'],
            'change_apply_time'=>time(),
            'change_over_time'=>$change_over_time
        ];

        $save = Db::name('order')
            ->where('id','=',$order_id)
            ->where('status','in',[1,2])
            ->update($change);
        if(!$save){
            throw new ServerException('订单申请状态保存失败');
        }

        $add = self::create([
            'order_id'=>$order_id,
            'note'=>$note,
            'imgs'=>json_encode($imgs)
        ]);
        if(!$add){
            throw new ServerException('换货信息表保存失败');
        }

        //推送给商家处理
        MerchNotice::send($order['merch_id'],'您的店铺有买家申请换货，请及时查看并处理','1',$order_id);

        return true;
    }

    /**
     * 取消换货
     * @param $order_id
     * @param $user
     * @param $merch_id
     * @return void
     * @throws ServerException
     * @throws UserException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    static public function changeCancel($order_id,$user=false,$merch_id=false){

        $where = [
            ['id','=',$order_id]
        ];

        if($user){
            $where[] = ['uid','=',$user['id']];
        }

        if($merch_id){
            $where[] = ['merch_id','=',$merch_id];
        }

        //订单
        $order = Db::name('order')
            ->where($where)
            ->field('id,order_sn,uid,merch_id,type,activity_type,verify_type,status,old_status')
            ->find();
        if(!$order){
            throw new UserException('无此订单或无权操作');
        }

        if($order['status']!=-4){
            throw new UserException('订单非申请换货状态无法驳回，请刷新');
        }

        $change = [
            'status'=>$order['old_status'],
            'change_apply_time'=>0,
            'change_over_time'=>0,
        ];

        $save = Db::name('order')
            ->where('id','=',$order_id)
            ->where('status','=',-4)
            ->update($change);
        if(!$save){
            throw new ServerException('订单状态保存失败');
        }

        //删除换货凭证记录
        self::where('order_id','=',$order_id)->delete();

        if(!$user){
            Notice::systemSend(2,$order['uid'],'换货申请已被驳回',"您的订单{$order['order_sn']}换货申请已被驳回",2,$order['id']);
        }
    }

    /**
     * 确认换货
     * @param $order_id
     * @param $send_express_id
     * @param $send_sn
     * @param $send_time
     * @return void
     * @throws ServerException
     * @throws UserException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    static public function confirmChange($order_id,$send_express_id,$send_sn,$send_time=false){

        $where = [
            ['id','=',$order_id]
        ];

        $order = Order::where($where)
            ->field('id,uid,merch_id,order_sn,type,activity_type,status,send_name,send_mobile,send_address,send_express_id,send_sn')
            ->find();

        if(!$order){
            throw new UserException('无此订单或无权操作');
        }

        if($order['status']!=-4){
            throw new UserException('订单非申请换货状态，不可换货');
        }

        if($order['type']!=2){
            throw new UserException(get_base_type(3,$order['type']).'订单不可换货');
        }

        //快递公司
        $send_arr = Settings::getSettings(ZFN_SETTINGS_EXPRESS);
        if(!isset($send_arr[$send_express_id])){
            throw new UserException('无此快递公司');
        }
        if($send_arr[$send_express_id]['status']!=1){
            throw new UserException($send_arr[$send_express_id]['title'].'已停止使用');
        }

        //快递单号
        $send_sn = reInject($send_sn);
        if(empty($send_sn)){
            throw new UserException('请输入快递单号，避免特殊字符');
        }

        $send_time = strtotime($send_time);
        if(!$send_time){
            $send_time = time();
        }

        $change = [
            'status'=>2,
            'send_express_id'=>$send_express_id,
            'send_express'=>$send_arr[$send_express_id]['title'],
            'send_sn'=>$send_sn,
            'send_time'=>$send_time,
            'is_change'=>1,
            'change_time'=>time()
        ];

        $save = Order::where('id',$order['id'])
            ->where('status',-4)
            ->update($change);
        if(!$save){
            throw new ServerException('换货信息保存失败，请稍后再试');
        }

        //通知买家换货了
        if($order['uid']){
            Notice::systemSend(2,$order['uid'],'订单换货提醒',"您的订单{$order['order_sn']}换货申请已通过，请注意查看物流",3,$order['id']);
        }
    }
}